import {
  addUserChannelAPI,
  delUserChannelAPI,
  getChannelAPI,
  getUserChannelAPI,
} from '@/api/channel';
import { getLocalChannels, getToken, setLocalChannels } from '@/utils/storage';
import { AppDispatch } from '..';
import { ChannelListType } from '../reducer/channel';

// 获取所有频道列表Action
export const getChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getChannelAPI();
    // console.log('channel', res);
    dispatch({ type: 'channel/saveallChanList', payload: res.data.channels });
  };
};
// 获取用户频道列表Action
export const getUserChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    // 1 有token时 从数据库中存储用户频道
    if (getToken()) {
      const res = await getUserChannelAPI();
      console.log('userchannel', res);
      dispatch({ type: 'channel/saveUserChanList', payload: res.data.channels });
      return;
    }

    // 2 没有token时
    const localChannel = getLocalChannels();
    // 2.1 本地没有缓存频道 先从数据库获取并存入本地 前10条即可
    if (!localChannel.length) {
      const res = await getChannelAPI();
      dispatch({ type: 'channel/saveUserChanList', payload: res.data.channels.slice(0, 10) });
      setLocalChannels(res.data.channels.slice(0, 10));
    } else {
      // 2.2 本地有缓存 从本地获取
      dispatch({ type: 'channel/saveUserChanList', payload: localChannel });
    }
  };
};
// 删除用户频道
export const delUserChannelAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    await delUserChannelAPI(id);
    dispatch({ type: 'channel/delUserChanList', payload: id });
  };
};

// 添加用户频道
export const addUserChannelAction = (channels: ChannelListType) => {
  return async (dispatch: AppDispatch) => {
    await addUserChannelAPI(channels);
    dispatch({ type: 'channel/addUserChanList', payload: channels });
  };
};

// 点谁谁高亮 改变currentId的值 头部action
export const handleKeyAction = (id: number) => {
  return { type: 'channel/changeCurrentId', payload: id };
};
